<?php

namespace App\Http\Middleware;

use App\Helpers\Api\ApiResponse;
use Closure;

class VerifySign
{
    use ApiResponse;

    private $secret = '#12912j#@!$';

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        \Log::info('--------start-sign----------');
//        if ($request->method() == 'POST') {
            $input = $request->input();
            null2none($input);
            if (!isset($input['sign']))
                return $this->failed('发送的数据签名不存在');

            if (!isset($input['timestamp']) || !$input['timestamp']) {
                return $this->failed('发送的数据参数不合法');
            }
            if (time() - $input['timestamp'] > 300) {
                return $this->failed('验证失效， 请重新发送请求');
            }

            $sign = $input['sign'];
            unset($input['sign']);
            ksort($input);
            $str = '';
            foreach ($input as $key => $val) {
                if (is_array($val)) {
                    $val = json_encode_cn($val);
                    $val = str_replace("\\/", "/", $val);
                }
                $str .= $key . '=' . $val . '&';
            }
            $str = rtrim($str, '&');

            $sign2 = md5($str . $this->secret);
            if ($sign != $sign2) {
                \Log::error('签名错误: ' . $str . $this->secret . ' my-sign ' . $sign2);
                return $this->failed('请求不合法');
            }

//        }
        return $next($request);
    }
}
